/*
@Time : 2018/11/9 下午9:06 
@Author : baoye
@File : blockchainIter
@Software: GoLand
@brief: 
*/

package main

import (
	"github.com/boltdb/bolt"
	"fmt"
	"os"
)

type BlockchainIter struct {

	db *bolt.DB
	currentHash []byte
}

func NewBlockchainIter(chain BlockChain) *BlockchainIter {

	blockchainIter := BlockchainIter{
		db:chain.db,
		currentHash:chain.tail,
	}
	return &blockchainIter
}

func (it *BlockchainIter)GetBlockAndMoveLeft() Block {
	var block Block
	it.db.Update(func(tx *bolt.Tx) error {
		bucket := tx.Bucket([]byte(BucketName))
		if bucket == nil {
			fmt.Println("bucket should not be nil!!")
			os.Exit(1)
		}else {
			info := bucket.Get(it.currentHash)
			block = Deserialize(info)

			// 指针左移
			it.currentHash = block.PrevBlockHash
		}
		return nil
	})

	return block
}

